#!/usr/bin/perl
# config_save.cgi
# Save inputs from config.cgi

require './web-lib.pl';
&init_config();
&ReadParse();
$m = $in{'module'};
&read_acl(\%acl);
&error_setup($text{'config_err'});
$acl{$base_remote_user,$m} || &error($text{'config_eaccess'});
%access = &get_module_acl(undef, $m);
$access{'noconfig'} && &error($text{'config_ecannot'});

mkdir("$config_directory/$m", 0700);
&lock_file("$config_directory/$m/config");
&read_file("$config_directory/$m/config", \%config);

if (-r "$m/config_info.pl") {
	# Module has a custom config editor
	&foreign_require($m, "config_info.pl");
	eval "\%${m}::in = \%in";
	&foreign_call($m, "config_save", \%config);
	}
else {
	# Use config.info to parse config inputs
	&read_file("$m/config.info", \%info, \@info_order) ||
		&error($text{'config_ecannot'});
	&read_file("$m/config.info.$gconfig{'lang'}", \%info, \@info_order);
	@info_order = &unique(@info_order);

	foreach $c (@info_order) {
		@p = split(/,/, $info{$c});
		if ($p[1] == 0 || $p[1] == 7 || $p[1] == 8) {
			# Free text input
			$config{$c} = $in{$c};
			}
		elsif ($p[1] == 1 || $p[1] == 4) {
			# One of many
			$config{$c} = $in{$c};
			}
		elsif ($p[1] == 5 || $p[1] == 6) {
			# User or group
			$config{$c} = ($p[2] && $in{$c."_def"} ? "" : $in{$c});
			}
		elsif ($p[1] == 2) {
			# Many of many
			$in{$c} =~ s/\0/,/g;
			$config{$c} = $in{$c};
			}
		elsif ($p[1] == 3) {
			# Optional free text
			if ($in{$c."_none"}) { $config{$c} = ""; }
			else { $config{$c} = $in{$c}; }
			}
		elsif ($p[1] == 9) {
			# Multilines of free text
			local $sp = $p[4] ? eval "\"$p[4]\"" : " ";
			$in{$c} =~ s/\r//g;
			$in{$c} =~ s/\n/$sp/g;
			$in{$c} =~ s/\s+$//;
			$config{$c} = $in{$c};
			}
		elsif ($p[1] == 10) {
			# One of many or free text
			if ($in{$c} eq 'free') {
				$config{$c} = $in{$c.'_free'};
				}
			else {
				$config{$c} = $in{$c};
				}
			}
		}
	}
&write_file("$config_directory/$m/config", \%config);
&unlock_file("$config_directory/$m/config");
&webmin_log("_config_", undef, undef, \%in, $m);
&redirect("/$m/");

